import eventbus from '@/until/eventbus'
const {SerialPort} = require('serialport')

function port(){
    const port = new SerialPort({
        path:'COM4',
        baudRate:9600,
        autoOpen:false
    })
    port.open()
    const buf = Buffer.from([0x50,0x03,0x00,0x3D,0x00,0x06,0x59,0x85])
    setInterval(()=>{
        port.write(buf)
    },1000)
    // buf.toString('hex')
    console.log('串口指令：',buf);
    port.drain(err=>{
        if(err)return;
        console.log('发送完成');
    })
    port.on('readable',()=>{
        let buf = port.read()
        // let str = buf.toString('hex')
        // let arr = [...str,4]
        let unit16array = new Uint16Array(buf)
        let arr =[]
        let x,y,z
        for(let i=0;i<unit16array.length;i++){
            arr[i] = unit16array[i].toString(16)
            if(arr[i].length==1){
                arr[i] = '0'+arr[i]
            }
        }
        if(arr[5]=='ff'){
            let num = parseInt(arr[5]+arr[6]+arr[3]+arr[4],16)
            x = -(~num+1)/1000
        }else{
            x = parseInt(arr[5]+arr[6]+arr[3]+arr[4],16)/1000
        }
        if(arr[9]=='ff'){
            let num = parseInt(arr[9]+arr[10]+arr[7]+arr[8],16)
            y = -(~num+1)/1000
        }else{
            y = parseInt(arr[9]+arr[10]+arr[7]+arr[8],16)/1000
        }
        if(arr[13]=='ff'){
            let num = parseInt(arr[13]+arr[14]+arr[11]+arr[12],16)
            z = -(~num+1)/1000
        }else{
            z = parseInt(arr[13]+arr[14]+arr[11]+arr[12],16)/1000
        }
        // console.log('数据接收：',buf);
        const axielObject = {
            x,y,z
        }
        // eventbus.emit('axiel',axielObject)
        console.log(axielObject.x,axielObject.y,axielObject.z);
        // console.log('数据接收(数组)：',arr);
    })

}

export default port